<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import {
  Edit,
  Delete
} from '@element-plus/icons-vue'

const tags = ref([
  // {
  //   "id": 3,
  //   "tagName": "美食",
  //   "createTime": "2023-09-02 12:06:59",
  // },
  // {
  //   "id": 4,
  //   "tagName": "美食",
  //   "createTime": "2023-09-02 12:06:59",
  // },
  // {
  //   "id": 5,
  //   "tagName": "美食",
  //   "createTime": "2023-09-02 12:06:59",
  // }, {
  //   "id": 5,
  //   "tagName": "美食",
  //   "createTime": "2023-09-02 12:06:59",
  // }, {
  //   "id": 5,
  //   "tagName": "美食",
  //   "createTime": "2023-09-02 12:06:59",
  // }, {
  //   "id": 5,
  //   "tagName": "美食",
  //   "createTime": "2023-09-02 12:06:59",
  // }, {
  //   "id": 5,
  //   "tagName": "美食",
  //   "createTime": "2023-09-02 12:06:59",
  // }, {
  //   "id": 5,
  //   "tagName": "美食",
  //   "createTime": "2023-09-02 12:06:59",
  // }, {
  //   "id": 5,
  //   "tagName": "美食",
  //   "createTime": "2023-09-02 12:06:59",
  // }, {
  //   "id": 5,
  //   "tagName": "美食",
  //   "createTime": "2023-09-02 12:06:59",
  // }, {
  //   "id": 5,
  //   "tagName": "美食",
  //   "createTime": "2023-09-02 12:06:59",
  // }, {
  //   "id": 5,
  //   "tagName": "美食",
  //   "createTime": "2023-09-02 12:06:59",
  // }, {
  //   "id": 5,
  //   "tagName": "美食",
  //   "createTime": "2023-09-02 12:06:59",
  // }, {
  //   "id": 5,
  //   "tagName": "美食",
  //   "createTime": "2023-09-02 12:06:59",
  // }, {
  //   "id": 5,
  //   "tagName": "美食",
  //   "createTime": "2023-09-02 12:06:59",
  // },
])

//名称搜索 
const search = ref('')
const filteredTags = computed(() => {
  if (search.value) {
    return tags.value.filter(tag =>
      tag.tagName.toLowerCase().includes(search.value.toLowerCase())
    )
  }
  return tags.value
})


// 从pinia中读取tags
import { useArticleStore } from '@/stores/articleStore';
const articleStore = useArticleStore();
// 获取分类数据
const getTagList = async () => {
  await articleStore.fetchTags(); // 调用 store 中的方法更新 categorys
  tags.value = articleStore.tags; // 将 store 中的数据赋值给组件内部的 categorys
};
const route = useRoute()

// 页面首次加载时获取分类数据
onMounted(() => {
  getTagList();
});
// 监听路由变化重新获取数据
watch(() => route.path, () => {
  getTagList()
})

// 调用接口添加表单
import { ElMessage } from 'element-plus';
const addTag = async () => {
  // 调用接口
  await articleStore.fetchTags(); // 先刷新分类列表
  let result = await TagAddService(tagModel.value);
  ElMessage.success(result.msg ? result.msg : '添加成功')
  // 调用获取所有文章分类的函数（刷新）
  getTagList();
  dialogVisible.value = false;
}

//添加分类数据模型
const tagModel = ref({
  tagName: '',
  tagCount: ''
})

//添加分类表单校验
const rules = {
  tagName: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
  ],
  tagCount: [
    { required: false, message: '非必要不建议修改', trigger: 'blur' },
  ]
}

// 定义变量，控制标题的展示
const title = ref('')

//控制添加分类弹窗
const dialogVisible = ref(false)

// 展示编辑弹窗
const showDialog = (row) => {
  dialogVisible.value = true; title.value = '编辑分类'
  // 数据拷贝
  tagModel.value.tagName = row.tagName;
  tagModel.value.articleCount = row.articleCount;
  // 扩展id属性，将来需要传给后台，完成分类的修改
  tagModel.value.id = row.id;
}

import { TagUpdateService, TagAddService, TagDeleteService } from '@/apis/article';
// 编辑分类
const updateTag = async () => {
  // 调用接口
  await articleStore.fetchTags(); // 先刷新分类列表
  let result = await TagUpdateService(tagModel.value);
  ElMessage.success(result.msg ? result.msg : '修改成功')
  // 调用获取所有文章分类的函数（刷新）
  getTagList();
  dialogVisible.value = false;
}

// 清空模型中的数据
const clearData = () => {
  tagModel.value.tagName = '';
  tagModel.value.articleCount = '';
}

// 删除分类
const deleteTag = (row) => {
  // 提示用户 确认框
  ElMessageBox.confirm(
    '确认删除该标签？',
    '温馨提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      // 调用接口 
      let result = await TagDeleteService(row.tagId || row.id);
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      // 刷新列表
      getTagList();
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="head">
        <div class="card-header">
          标签管理
        </div> 
        <el-button type="primary" @click="dialogVisible = true; title = '添加标签'; clearData()" class="add-button">+添加分类</el-button>
      </div>
    </template>

    <div class="article-management">
      <!-- 名字搜索 -->
      <div class="search">
        <el-input
          v-model="search"
          placeholder="搜索分类..."
          style="width: 50vh;"
          :prefix-icon="Search"
        />
      </div>
      
      <el-table
        :data="filteredTags"
        :row-style="{ height: '50px' }"
        :cell-style="{ paddingTop: '2.5px' }"
        style="width: 100%; font-size: 15px"
      >
        <el-table-column label="标签名称" width="400" prop="tagName"></el-table-column>
        <el-table-column label="创建时间" prop="createdTime"></el-table-column>
        <el-table-column label="标签文章数量" prop="articleCount"></el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
            <el-button :icon="Delete" circle plain type="danger" @click="deleteTag(row)"></el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="没有数据" />
        </template>
      </el-table>
    </div>

     <!-- 添加分类弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="30%">
      <el-form :model="tagModel" :rules="rules" label-width="100px" style="padding-right: 30px">
          <el-form-item label="标签名称" prop="tagName">
              <el-input v-model="tagModel.tagName" minlength="1" maxlength="10"></el-input>
          </el-form-item>
          <el-form-item label="文章数量" prop="articleCount">
              <el-input v-model="tagModel.articleCount" placeholder="非必要不建议修改" minlength="1" maxlength="15"></el-input>
          </el-form-item>
      </el-form>
      <template #footer>
          <span class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="title == '添加标签' ? addTag() : updateTag()"> 确认 </el-button>
          </span>
      </template>
    </el-dialog>

  </el-card>
</template>



<style>
.page-container {
  min-height: 86.5vh;
  box-sizing: border-box;

  .head {
    display: flex;

    .card-header {
      text-align: center;
      font-size: 25px;
    }

    .add-button {
      margin-left: auto;
      margin-top: 5px;
    }

  }
}

.el-card {
  background-color: #ffffff;
  margin: 10px;
  height: auto;

  /* 让RouterView占用剩余空间 */
  .search {
    padding-left: 12px;
    padding-bottom: 10px;

    & input {
      width: 40vh;
      height: 4vh;
    }
  }

  .el-form {
    padding-top: 10px;
  }

  .el-table-column {
    height: 100px;
  }

}
</style>